package Method_01;

public class PollableNode<T extends Comparable<T>> extends Thread {

	public PollableNode<T> left;
	public PollableNode<T> right;
	
	private final PollGroup<T> pg;
	
	private T value;
	
	/**
	 * Constructs the PollableNode
	 * 
	 * @param pg : The PollGroup that this node belongs to
	 * @param value : Value of this node
	 */
	public PollableNode(PollGroup<T> pg, T value){
		super();
		this.pg = pg;
		this.value = value;
	}
	
	/**
	 * Get the value of this node
	 * 
	 * @return the Value
	 */
	public T getValue(){
		return value;
	}
	
	/**
	 * constantly checking for a new poll, and it writes to the response if it satisfies the poll
	 */
	@Override
	public void run() {
		while (true){
			Poll<T> p = pg.getPoll();
			if (p != null){
				switch(p.isSuccess(this)){
				case 0:
					// failed to succeed
					break;
				
				case 1:
					pg.setResponse(this);
					break;
					
				case -1:
					pg.atBeginning();
					break;
				
				case 2:
					pg.atEnd();
					break;
					
				default:
					System.err.print("Unhandled output");
					break;
				} 
			}
		}
	}

	public int compareTo(PollableNode<T> pn) {
		return value.compareTo(pn.getValue());
	}
	
	public int compareTo(T value) {
		return this.value.compareTo(value);
	}
	
	public String toString(){
		return this.value.toString();
	}
	
}
